<template>
  <v-card-text>
    <material-card color="green darken-1">
      <template v-slot:header>
        <div class="px-3">
          <div class="title font-weight-light mb-2">
            评论
          </div>

          <div class="category">
            欢迎灌水~
            <v-icon size="17">
              mdi-heart
            </v-icon>
          </div>
        </div>
      </template>

      <v-card-text>
        <div class="text-center">
          <h2 class="title font-weight-light mb-2">
            随便刷点啥
          </h2>
          <span class=" subheading font-weight-light grey--text">
            有趣的灵魂在哪里？
          </span>
        </div>

        <v-container>
          <v-sheet width="100%">
            <v-textarea
              v-model="commentValue"
              :auto-grow="true"
              :clearable="true"
              :rounded="true"
              :solo="true"
              hint="多少说一个字吧"
              label="评论"
              placeholder="写下你的评论"
              :tile="false"
            />
            <v-card elevation="0" class="text-right" width="100%">
              <v-btn right color="green darken-1" dark @click="pointFingers">提交</v-btn>
            </v-card>
          </v-sheet>
          <!-- 和平友善的分割线  -->
          <v-divider class="mt-8" />
          <div class="container">
            <div v-for="(item, index) in commentData" :key="'comment-'+index" class="comment">
              <div class="info">
                <img class="avatar" :src="item.avatar" width="36" height="36" alt="avatar">
                <div class="right">
                  <div class="name">{{ item.name }}</div>
                  <div class="date">{{ item.createTime | 1 }}</div>
                </div>
              </div>
              <div class="content">{{ item.content }}</div>
              <div class="control">
                <span class="like" :class="{active: item.isLike}" @click="likeClick(item)">
                  <v-icon
                    class="iconfont"
                    :color="item.isLike ? 'blue lighten-2':''"
                  >mdi-thumb-up-outline</v-icon>
                  <span class="like-num">{{ item.likeNum > 0 ? item.likeNum + '人赞' : '赞' }}</span>
                </span>
                <span class="comment-reply" @click="showCommentInput(item)">
                  <v-icon class="iconfont">mdi-comment-processing-outline</v-icon>
                  <span>回复</span>
                </span>
              </div>
              <div class="reply">
                <div v-for="(reply, index) in item.reply" :key="'reply-'+index" class="item">
                  <div class="reply-content">
                    <span class="from-name">{{ reply.reviewerName }}</span><span>: </span>
                    <span class="to-name">@{{ reply.commentatorName }}</span>
                    <span>{{ reply.content }}</span>
                  </div>
                  <div class="reply-bottom">
                    <span>{{ reply.createTime | dateformat("YYYY-MM-DD HH:mm:ss") }}</span>
                    <span class="reply-text" @click="showCommentInput(item, reply)">
                      <v-icon class="iconfont">mdi-comment-processing-outline</v-icon>
                      <span>回复</span>
                    </span>
                  </div>
                </div>
                <div v-if="item.reply.length > 0" class="write-reply" @click="showCommentInput(item)">
                  <i class="el-icon-edit iconfont" />
                  <span class="add-comment">添加新评论</span>
                </div>
                <transition name="fade">
                  <div v-if="showItemId === item.id" class="input-wrapper">
                    <el-input
                      v-model="inputComment"
                      class="gray-bg-input"
                      type="textarea"
                      :rows="3"
                      autofocus
                      placeholder="写下你的评论"
                    />
                    <div class="btn-control">
                      <span class="cancel" @click="cancel">取消</span>
                      <el-button class="btn" type="success" round @click="commitComment(item)">确定
                      </el-button>
                    </div>
                  </div>
                </transition>
              </div>
            </div>
          </div>
          <el-pagination
            v-if="commentData.length > 0"
            :current-page="current"
            :page-size="pageSize"
            :page-sizes="[10,20,30]"
            layout="total, sizes ,prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </v-container>
      </v-card-text>
    </material-card>
  </v-card-text>
</template>

<script>
import '@/assets/css/business/blog/detail/comments/comment.scss'
import { doComments, getCommentList, replyComments, likeOrNot } from '@/api/blog'

export default {
  name: 'Comments',
  props: {
    blogId: {
      type: Number,
      required: true
    }
  },
  data: () => ({
    commentData: [],
    commentValue: '', // 用户评论的内容
    current: 1, // 初始时是第几页
    pageSize: 10, // 一页需要展示多少条博客
    size: 0, // 当前总共有多少页，根据后台回传的参数计算
    total: 0, // 总数
    pages: 0, // 总页数
    inputComment: '',
    showItemId: ''
  }),
  created() {
    this.getCommentDataByBlogId()
  },
  methods: {
    // 后端请求
    pointFingers() {
      // 评论内容不能为空
      if (this.commentValue === '') {
        this.$iziToast.warning({ message: '评论内容不能为空，不要写无字天书好吗，宝贝' })
        return
      }
      const params = {
        blogId: this.blogId,
        content: this.commentValue
      }
      doComments(params)
        .then((res) => this.doCommentSuccess(res))
        .catch(err => this.doCommentFailed(err))
        .finally(() => {
          // console.log("评论完成......")
        })
    },
    getCommentDataByBlogId() {
      const params = {
        blogId: this.blogId,
        current: this.current,
        pageSize: this.pageSize
      }
      getCommentList(params)
        .then((res) => this.getCommentListSuccess(res))
        .catch(err => this.getCommentListFailed(err))
        .finally(() => {
          // console.log("获取评论列表完成......")
        })
    },
    // 提交评论
    commitComment(item) {
      const params = {
        commentId: item.id,
        commentatorId: item.reviewerId,
        content: this.inputComment.replace('@' + item.name, '')
      }
      replyComments(params)
        .then((res) => this.replySuccess(res))
        .catch(err => this.replyFailed(err))
        .finally(() => {
          // console.log("回复评论完成......")
        })
    },
    // 设置分页属性
    setPaginations(page) {
      this.current = page.current
      this.total = page.total
      this.pageSize = page.size
      this.pages = page.pages
    },
    // 我喜欢
    ilikeIt(commentId, like) {
      const params = {
        like: like,
        commentId: commentId
      }
      likeOrNot(params)
        .then(res => {
          // console.log("点赞成功" + res);
        })
        .catch(err => {
          // console.log("点赞出错" + err);
        })
        .finally(() => {
          // console.log("点赞完成......")
        })
    },
    // 点赞
    likeClick(item) {
      if (item.isLike === null) {
        this.$set(item, 'isLike', true)
        this.ilikeIt(item.id, 1)
        item.likeNum++
      } else {
        if (item.isLike) {
          this.ilikeIt(item.id, 0)
          item.likeNum--
        } else {
          this.ilikeIt(item.id, 1)
          item.likeNum++
        }
        item.isLike = !item.isLike
      }
    },
    // 点击评论按钮显示输入框
    showCommentInput(item, reply) {
      if (reply) {
        this.inputComment = '@' + reply.reviewerName + ' '
      } else {
        this.inputComment = ''
      }
      this.showItemId = item.id
    },
    // 清空回复界面
    clearReplyArea() {
      this.inputComment = ''
      this.showItemId = ''
    },
    // 点击取消按钮
    cancel() {
      this.showItemId = ''
    },
    // 页面尺寸变更
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getCommentDataByBlogId()
    },
    // 改变当前页
    handleCurrentChange(current) {
      this.current = current
      this.getCommentDataByBlogId()
    },
    // 回调分流
    replySuccess(res) {
      if (res.code === 200) {
        this.clearReplyArea()
        this.$iziToast.success({ message: res.msg })
        this.getCommentDataByBlogId()
      }
    },
    replyFailed(err) {
      // console.log('回复评论失败', err)
    },
    getCommentListSuccess(res) {
      const resultData = res.data
      if (res && res.code === 200) {
        this.commentData = []
        this.commentData.push(...resultData.records)
        this.setPaginations(resultData)
      }
    },
    getCommentListFailed(err) {
      // console.log('获取评论列表失败', err)
    },
    doCommentSuccess(res) {
      if (res && res.code === 200) {
        this.commentValue = ''
        this.getCommentDataByBlogId()
        this.$iziToast.success({ message: res.msg })
      }
    },
    doCommentFailed(err) {
      // console.log('评论失败', err)
    }
  }
}
</script>

<style scoped>

</style>
